package com.phamkhanh.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

@WebServlet(urlPatterns = { "/upload.jsp" })
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public UploadServlet() {
        super();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("upload.jsp");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		response.setContentType("text/plain");
		try{
			if(ServletFileUpload.isMultipartContent(request)){
				List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
				for(FileItem item : items){
					if(item.isFormField()){
						String fieldName = item.getFieldName();
						String fieldValue = item.getString();
						System.out.println("FieldName : "+ fieldName +"/nFieldValue : "+fieldValue);
					}else{
						String fieldName = item.getFieldName();
						String fileName = FilenameUtils.getName(item.getName());
						String contentType = item.getContentType();
						boolean isInMemory = item.isInMemory();
						long size = item.getSize();
						byte[] audioBytes = item.get();
						String result = processAudio(audioBytes);
						writer.print(result);
						System.out.println("FieldName : "+ fieldName);
						System.out.println("FileName : "+ fileName);
						System.out.println("ContentType : "+ contentType);
						System.out.println("IsInMemory : "+ isInMemory);
						System.out.println("Size : "+ size);
					}
				}
			}
			writer.flush();
			writer.close();
		}catch(FileUploadException e){
			e.printStackTrace();
		}
	}
	
	/** Xử lí audio trả về và gửi lại lệnh mà người dùng mong muốn. */
	protected String processAudio(byte[] audioBytes){
		return "CTRL+T";
	}

}
